<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="10" :lg="11" :md="12" :sm="24">
            <a-form-item :label="$t('业务时间')">
              <j-date
                :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
                valueFormat="YYYY-MM-DD HH:mm:ss"
                dateFormat="YYYY-MM-DD HH:mm:ss"
                :placeholder="$t('请选择开始时间')"
                class="query-group-cust"
                v-model="queryParam.createTime_begin"
              ></j-date>
              <span class="query-group-split-cust"></span>
              <j-date
                :show-time="{ defaultValue: moment('23:59:59', 'HH:mm:ss') }"
                valueFormat="YYYY-MM-DD HH:mm:ss"
                dateFormat="YYYY-MM-DD HH:mm:ss"
                :placeholder="$t('请选择结束时间')"
                class="query-group-cust"
                v-model="queryParam.createTime_end"
              ></j-date>
            </a-form-item>
          </a-col>
          <a-col :xl="7" :lg="7" :md="8" :sm="24">
            <a-form-item :label="$t('出入库单号')">
              <a-input :placeholder="$t('请输入出入库单号')" v-model="queryParam.orderId"></a-input>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item :label="$t('出入库类型')">
                <j-dict-select-tag
                  :placeholder="$t('请选择出入库类型')"
                  v-model="queryParam.orderType"
                  dictCode="bis_goods_stock_order.order_type"
                />
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item :label="$t('关联业务单号')">
                <a-input :placeholder="$t('请输入关联业务单号')" v-model="queryParam.bisOrderId"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item :label="$t('业务类型')">
                <j-dict-select-tag
                  :placeholder="$t('请选择业务类型')"
                  v-model="queryParam.bisType"
                  dictCode="bis_goods_stock_change.bis_type"
                />
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item :label="$t('仓库')">
                <a-tree-select
                  allowClear
                  v-model="queryParam.storeId"
                  style="width: 100%"
                  :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                  :tree-data="storeList"
                  :search-placeholder="$t('请选择')"
                />
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item :label="$t('编码（名称）')">
                <a-select
                  v-model="queryParam.goodsId"
                  show-search
                  :placeholder="$t('请选择商品')"
                  :filter-option="false"
                  :not-found-content="null"
                  @search="handleGoodsSearch"
                >
                  <a-select-option v-for="good in goodsList" :key="good.id">{{ good.code?(good.code+'('+good.name+')'):good.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item :label="$t('操作员')">
                <a-input :placeholder="$t('请输入操作员')" v-model="queryParam.createBy"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="5" :lg="5" :md="6" :sm="24" v-if="!tenantid">
              <a-form-item :label="$t('门店')">
                <a-select v-model="queryParam.tenantId">
                  <a-select-option v-for="(item, i) in shops" :key="i" :value="item.value"
                    >{{ item.title
                    }}<span v-if="item.value != '' && item.value != '0'">（{{ item.value }}）</span></a-select-option
                  >
                </a-select>
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">{{ $t('查询') }}</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">{{
                $t('重置')
              }}</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? $t('收起') : $t('展开') }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" :loading="exloading" @click="handleExportXls($t('库存变化明细'))" v-has="'BisGoodsStockChangeController:export'">{{ $t('导出') }}</a-button>
      <!-- <a-button type="primary" v-print="'#printme'">{{ $t('打印') }}</a-button> -->
    </div>

    <!-- table区域-begin -->
    <div id="printme">
      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: true }"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      >
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">{{ $t('无图片') }}</span>
          <img
            v-else
            :src="getImgView(text)"
            height="25px"
            alt=""
            style="max-width: 80px; font-size: 12px; font-style: italic"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">{{ $t('无文件') }}</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
            {{ $t('下载') }}
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleDetail(record)">{{ $t('详情') }}</a>
        </span>
        <template slot="footer">
          <div style="font-weight: bold">
            <span style="margin-right: 5px">{{$t('合计')}}：</span>
            <span style="margin-right: 5px">{{$t('业务数量')}}：</span>
            <span>{{ totalInfo.bisNum ? totalInfo.bisNum.toFixed(0) : 0 }}</span>
            <span style="margin-left: 15px;margin-right: 5px">{{$t('业务金额')}}：</span>
            <span>{{ totalInfo.cost ? totalInfo.cost.toFixed(2):'0.00'}}</span>
          </div>
        </template>
      </a-table>
    </div>

    <bis-goods-stock-change-modal ref="modalForm" @ok="modalFormOk"></bis-goods-stock-change-modal>
  </a-card>
</template>

<script>
import moment from 'moment'
import '@/assets/less/TableExpand.less'
import Vue from 'vue'
import { TENANT_ID } from '@/store/mutation-types'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
import { getAction } from '@/api/manage'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import BisGoodsStockChangeModal from './modules/BisGoodsStockChangeModal'

export default {
  name: 'BisGoodsStockChangeList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    BisGoodsStockChangeModal,
  },
  data() {
    return {
      description: '库存变化明细管理页面',
      moment,
      // 表头
      columns: [
        {
          title: this.$t('业务时间'),
          align: 'center',
          dataIndex: 'createTime',
        },
        {
          title: this.$t('出入库单号'),
          align: 'center',
          dataIndex: 'orderId',
        },
        {
          title: this.$t('出入库类型'),
          align: 'center',
          dataIndex: 'orderType_dictText',
        },
        {
          title: this.$t('关联业务单号'),
          align: 'center',
          dataIndex: 'bisOrderId',
        },
        {
          title: this.$t('业务类型'),
          align: 'center',
          dataIndex: 'bisType_dictText',
        },
        {
          title: this.$t('仓库'),
          align: 'center',
          dataIndex: 'storeId_dictText',
        },
        {
          title: this.$t('商品编码'),
          align: 'center',
          dataIndex: 'goodsCode',
        },
        {
          title: this.$t('商品名称'),
          align: 'center',
          dataIndex: 'goodsId_dictText',
        },
        {
          title: this.$t('业务前数量'),
          align: 'right',
          dataIndex: 'beforeNum',
          customRender: (text, r) => {
            return text.toFixed(0);
          }
        },
        {
          title: this.$t('业务前库存金额'),
          align: 'right',
          dataIndex: 'beforeAmount',
          customRender: (text, r) => {
            return text.toFixed(2);
          }
        },
        {
          title: this.$t('业务数量'),
          align: 'right',
          dataIndex: 'bisNum',
          customRender: (text, r) => {
            return text.toFixed(0);
          }
        },
        {
          title: this.$t('业务金额'),
          align: 'right',
          dataIndex: 'cost',
          customRender: (text, r) => {
            return text.toFixed(2);
          }
        },
        {
          title: this.$t('业务后数量'),
          align: 'right',
          dataIndex: 'afterNum',
          customRender: (text, r) => {
            return text.toFixed(0);
          }
        },
        {
          title: this.$t('业务后库存金额'),
          align: 'right',
          dataIndex: 'afterAmount',
          customRender: (text, r) => {
            return text.toFixed(2);
          }
        },
        {
          title: this.$t('操作员'),
          align: 'center',
          dataIndex: 'createBy',
        },
        {
          title: this.$t('设备编码'),
          align: 'center',
          dataIndex: 'deviceId',
        },
        {
          title: this.$t('备注'),
          align: 'center',
          dataIndex: 'comment',
        },
      ],
      url: {
        list: '/goods/bisGoodsStockChange/list',
        delete: '/goods/bisGoodsStockChange/delete',
        deleteBatch: '/goods/bisGoodsStockChange/deleteBatch',
        exportXlsUrl: '/goods/bisGoodsStockChange/exportXls',
        importExcelUrl: 'goods/bisGoodsStockChange/importExcel',
        totalUrl: "/goods/bisGoodsStockChange/total"
      },
      dictOptions: {},
      superFieldList: [],
      goodsList: [],
      storeList:[],
      isfooter: true,
      queryParam:{
        storeId:'',
        tenantId: ''
      },
      isorter: {
        column: 'id',
        order: 'desc',
      },
      shops: [],
      tenantid: Vue.ls.get(TENANT_ID),
    }
  },
  created() {
    this.getSuperFieldList()
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    initDictConfig() {
      this.getStoreList()
      if (!this.tenantid) {
        initDictOptions('bis_shop,name,code').then((res) => {
          if (res.success) {
            this.shops = res.result
            this.shops.unshift({ value: '0', title: this.$t('总部') })
            this.shops.unshift({ value: '', title: this.$t('全部') })
          }
        })
        this.columns.push({
          title: this.$t('所属门店'),
          align: 'left',
          dataIndex: 'tenantId',
          customRender: (t, r) => {
            let str
            if (t == 0) {
              str = this.$t('总部')
            } else {
              str = r.tenantId_dictText ? t + ' ' + r.tenantId_dictText : t
            }
            return str
          },
        })
      }
    },
    getStoreList() {
      let that = this
      let storeList = []
      let param = {}
      param.pageNo = 1
      param.pageSize = 9999
      param.column = 'id'
      param.order = 'DESC'
      getAction('/goods/bisGoodsStore/rootList', param).then((res) => {
        if (res.success) {
          that.allChildKind = []
          storeList = res.result.records
          if (storeList.length > 0) {
            storeList.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.id = '' + col.id
              col.pid = '' + col.pid
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                that.getHasChildStore(col)
              }
            })
            that.storeList = that.getDataByResult(storeList)
            that.storeList.unshift({ key: '', id: '', value:'', title: that.$t('全部') })
          }
        }
      })
    },
    getHasChildStore(store) {
      let that = this
      let query = {}
      query.pageNo = 1
      query.pageSize = 9999
      query.pid = store.id
      getAction('/goods/bisGoodsStore/rootList', query).then((res) => {
        if (res.success) {
          if (res.result.records.length > 0) {
            res.result.records.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.pid = '' + col.pid
              col.id = '' + col.id
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                that.getHasChildStore(col)
              }
            })
            store.children = that.getDataByResult(res.result.records)
            that.storeList = [...that.storeList]
          }
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    getDataByResult(result) {
      return result.map((item) => {
        return item
      })
    },
    searchReset(){
      this.queryParam={
        storeId:'',
        tenantId: ''
      }
      this.searchQuery()
    },
    handleGoodsSearch(value) {
      let querydata = {}
      querydata.pageIndex = 1
      querydata.pageSize = 10
      querydata.form = '1,7,11,12,19'
      querydata.goodsInfo = value
      getAction('/goods/bisGoodsInfor/list', querydata).then((res) => {
        if (res.success) {
          this.goodsList = res.result.records
        }
      })
    },
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'datetime', value: 'createTime', text: this.$t('业务时间') })
      fieldList.push({ type: 'string', value: 'orderId', text: this.$t('出入库单号'), dictCode: '' })
      fieldList.push({
        type: 'int',
        value: 'orderType',
        text: this.$t('出入库类型'),
        dictCode: 'bis_goods_stock_order.order_type',
      })
      fieldList.push({ type: 'string', value: 'bisOrderId', text: this.$t('关联业务单号'), dictCode: '' })
      fieldList.push({
        type: 'string',
        value: 'bisType',
        text: this.$t('业务类型'),
        dictCode: 'bis_goods_stock_change.bis_type',
      })
      fieldList.push({ type: 'string', value: 'storeId', text: this.$t('仓库'), dictCode: 'bis_goods_store,name,id' })
      fieldList.push({
        type: 'sel_search',
        value: 'goodsId',
        text: this.$t('卖品'),
        dictTable: 'bis_goods_infor',
        dictText: 'name',
        dictCode: 'id',
      })
      fieldList.push({ type: 'int', value: 'beforeNum', text: this.$t('业务前数量'), dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'beforeAmount', text: this.$t('业务前库存金额'), dictCode: '' })
      fieldList.push({ type: 'int', value: 'bisNum', text: this.$t('业务数量'), dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'cost', text: this.$t('库存成本'), dictCode: '' })
      fieldList.push({ type: 'int', value: 'afterNum', text: this.$t('业务后数量'), dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'afterAmount', text: this.$t('业务后库存金额'), dictCode: '' })
      fieldList.push({ type: 'string', value: 'createBy', text: this.$t('操作员'), dictCode: '' })
      this.superFieldList = fieldList
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>